<template>
  <div>

    <div>
      <!-- 模糊搜索 -->
      <el-card style="height: 50px" :body-style="{ padding: '10px', height: '50px', width: '80%'}">
        <div class="box-card-div">
          <el-form :inline="true" :model="orderRefundDTO" ref="orderRefundDTOForm" class="demo-form-inline">
            <el-form-item label="订单id" prop="orderId">
              <el-input size="small" v-model="orderRefundDTO.orderId" placeholder="请输入订单id"></el-input>
            </el-form-item>
            <el-form-item label="用户id" prop="userId">
              <el-input size="small" v-model="orderRefundDTO.userId" placeholder="请输入用户id"></el-input>
            </el-form-item>
            <!-- todo 退款申请时间的格式设置问题，报400错误，暂时注释掉-->
            <el-form-item label="退款申请时间" prop="refundAt">
              <el-date-picker
                v-model="orderRefundDTO.refundAt"
                type="datetime"
                placeholder="选择退款时间"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="退款状态" prop="status">
              <el-select size="small" v-model="orderRefundDTO.status">
                <el-option label="待审核" value="0"></el-option>
                <el-option label="退款中" value="1"></el-option>
                <el-option label="退款成功" value="2"></el-option>
                <el-option label="拒绝" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="success" round size="small" @click="onSearch" icon="el-icon-search">查询</el-button>
              <el-button type="warning" round size="small" @click="resetOrderRefundDTOForm('orderRefundDTOForm')"
                         icon="el-icon-refresh-left">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>

      <!-- 添加和批量删除按钮 -->
      <div class="button-container">
        <el-button class="btn_add" type="primary" @click="handleAddOrderRefund" size="middle" icon="el-icon-plus">新增</el-button>
        <el-button class="btb_del" type="danger" @click="deleteOrderRefundBatch" size="middle" icon="el-icon-delete">批量删除</el-button>
      </div>
      <el-dialog
        :title="title"
        :visible.sync="editDialogVisible"
        width="40%"
        :close-on-click-modal="false"
      >
        <el-form ref="orderRefundForm" :model="orderRefund" :rules="rules" label-width="100px">
          <el-form-item label="退款编号" prop="id">
            <el-input v-model="orderRefund.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="订单Id" prop="orderId" width="150px">
            <el-input v-model="orderRefund.orderId"></el-input>
          </el-form-item>
          <el-form-item label="用户Id" prop="userId" width="150px">
            <el-input v-model="orderRefund.userId"></el-input>
          </el-form-item>
          <el-form-item label="退款总金额" prop="refundAmount" width="100px">
            <el-input v-model.number="orderRefund.refundAmount"></el-input>
          </el-form-item>
          <el-form-item label="退款原因" prop="reason" width="300px">
            <el-input v-model="orderRefund.reason"></el-input>
          </el-form-item>
          <el-form-item label="退款状态" prop="status" width="100px">
            <el-select v-model="orderRefund.status">
            <!-- 退款状态 0待审核 1退款中 2退款成功 3拒绝-->
              <el-option label="待审核" value="0"></el-option>
              <el-option label="退款中" value="1"></el-option>
              <el-option label="退款成功" value="2"></el-option>
              <el-option label="拒绝" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="退款时间" prop="refundAt" width="300px">
            <el-date-picker
              v-model="orderRefund.refundAt"
              type="date"
              placeholder="选择退款时间"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer" style="width: 200px;">
          <el-button @click="resetOrderRefundDTOForm('orderRefundForm')">取 消</el-button>
          <el-button type="primary" @click="saveOrderRefund('orderRefundForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 表格 -->
    <div>
      <el-table
        :data="tableData"
        border
        class="orderRefund-table"
        style="width: 100%"
        row-key="id"
        default-expand-all
        height="500"
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
         >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="退单编号" width="100px"></el-table-column>
        <el-table-column prop="orderId" label="订单编号" width="100px"></el-table-column>
        <el-table-column prop="userId" label="用户编号" width="100px"></el-table-column>
        <el-table-column prop="refundAmount" label="退款金额" width="100px"></el-table-column>
        <el-table-column prop="reason" label="退款原因" width="150px"></el-table-column>
        <el-table-column prop="status" label="退款状态" width="100px">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 0" type="warning">待审核</el-tag>
            <el-tag v-if="scope.row.status === 1" type="info">退款中</el-tag>
            <el-tag v-if="scope.row.status === 2" type="success">退款成功</el-tag>
            <el-tag v-if="scope.row.status === 3" type="danger">拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="refundAt" label="退款时间" width="200px" type="datetime" format="yyyy-MM-dd HH:mm:ss">
          <template slot-scope="scope">
            {{ scope.row.refundAt}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleOrderRefundEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleOrderRefundDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        :page-sizes="pageSizes"
        @current-change="handleCurrentChange"
        :current-page="orderRefundDTO.pageNum"
        :page-size="orderRefundDTO.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <el-button class="button_to_page" style="margin-left: 10px" size="small" type="primary" plain @click="toPage">跳转</el-button>
    </div>
  </div>
    </div>
</template>

<script>
import {
  addOrderRefund,
  deleteOrderRefund,
  deleteOrderRefundBatch,
  findAll,
  updateOrderRefund
} from '@/api/order/orderRefund'
export default {
  name: "OrderRefund",
  data() {
    return {
      tableData: [],
      pageSizes: [3, 5, 10, 20],
      editDialogVisible: false,
      multipleSelection: [],
      orderRefund: {
        id: null,
        orderId: null,
        userId: null,
        refundAmount: null,
        refundReason: null,
        status: null,
        refundAt: null,
      },
      orderRefundDTO: {
        orderId: null,
        userId: null,
        refundAt: null,
        status: null,
        pageNum: 1,
        pageSize: 3,
      },
      total: 0,
      editOrderRefundDialog: false,
      title: "添加退款记录",
      rules: {
        orderId: [
          { required: true, message: "请输入退单编号", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
        ],
        userId: [
          { required: true, message: "请输入用户Id", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
        ],
        refundAmount: [
          { required: true, message: "请输入订单总金额", trigger: "blur" },
          { type: "number", message: "请输入正确的订单总金额", trigger: "blur" },
        ],
        reason: [ { required: true, message: "请输入退款原因", trigger: "blur" } ],
        status: [
          { required: true, message: "请选择订单状态", trigger: "blur" },
        ],
        refundAt: [
          { required: true, message: "请选择退款申请时间", trigger: "blur" },
        ],
    }
  }
  },
  methods: {
    onSearch(){
      this.findAll();
    },
    findAll() {
      findAll(this.orderRefundDTO).then(res => {
          this.tableData = res.data.list
          this.total = res.data.total
        })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.orderRefundDTO.pageNum = 1;
      this.findAll();
    },
    handleSizeChange(val) {
      this.orderRefundDTO.pageSize = val
      this.findAll()
    },
    handleCurrentChange(val) {
      this.orderRefundDTO.pageNum = val
      this.findAll()
    },
    toPage() {
      this.findAll()
    },
    // 复选框点击事件
    handleSelectionChange(val) {
      this.multipleSelection = [];
      for (let i = 0; i < val.length; i++) {
        this.multipleSelection.push(val[i].id)
      }
    },
    // 通过订单id删除订单
    handleOrderRefundDelete(index, row) {
      // 首先要进行弹框提示
      this.$confirm("是否确认删除退款编号为" + '"' + row.id + '"' + "的数据项？", '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = row.id;
        deleteOrderRefund(id).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderRefundDTO.pageNum = 1;
            this.findAll()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 批量删除订单
    deleteOrderRefundBatch(){
      this.$confirm("是否确认删除选中的" + this.multipleSelection.length + "条数据项？", '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrderRefundBatch(this.multipleSelection).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderRefundDTO.pageNum = 1;
            this.findAll()
            // 批量删除成功后，需要清空已选择的行
            this.multipleSelection = [];
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 点击修改按钮，触发修改对话框
    async handleOrderRefundEdit(index, row) {
      this.title = "修改订单";
      this.editDialogVisible = true;
      // 等待对话框完全打开
      await this.$nextTick();
      // 先重置表单（这会清除所有校验状态）
      this.$refs.orderRefundDTOForm.resetFields();
      // 深拷贝数据
      this.orderRefund = JSON.parse(JSON.stringify(row));
      // 转换日期格式
      this.convertDateFields();
      // 再次确保清除校验状态
      await this.$nextTick();
      // todo:清除校验状态没有生效
      this.$refs.orderRefundDTOForm.clearValidate();
    },
    // 添加一个专门处理日期字段的方法
    convertDateFields() {
      const dateFields = ['createdAt'];
      dateFields.forEach(field => {
        if (this.orderRefund[field]) {
          this.orderRefund[field] = new Date(this.orderRefund[field]);
        }
      });
    },
    // 点击新增按钮，触发新增对话框
    handleAddOrderRefund() {
      this.title = "添加订单";
      this.orderRefund = { };
      this.editDialogVisible = true;
      this.$refs.orderRefundDTOForm.resetFields(); // 重置表单校验状态
    },
    // 点击保存按钮，触发保存事件
    saveOrderRefund(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === "添加退款记录") {
            addOrderRefund(this.orderRefund).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '新增成功!',
                  duration: 1000
                })
                this.editDialogVisible = false;
                this.orderRefundDTO.pageNum = 1;
                this.findAll()
                this.resetOrderRefundDTOForm(formName)
              } else {
                this.$message({
                  type: 'error',
                  message: '新增失败!',
                  duration: 1000
                })
              }
            })
          } else {
            updateOrderRefund(this.orderRefund).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '修改成功!',
                  duration: 1000
                })
                this.editDialogVisible = false;
                this.orderRefundDTO.pageNum = 1;
                this.findAll()
                this.resetOrderRefundDTOForm(formName)
              } else {
                this.$message({
                  type: 'error',
                  message: '修改失败!',
                  duration: 1000
                })
              }
            })
          }
        } else {
          return false;
        }
      })
    },
    // 重置表单
    resetOrderRefundDTOForm(formName) {
      // 关闭对话框
      this.editDialogVisible = false;
      // 延迟一下，确保表单控件都渲染完毕
      this.$nextTick(() => {
        this.$refs[formName].resetFields(); // 重置表单校验状态
      });
    },
  },
  created() {
    this.findAll()
  }
}

</script>

<style scoped>
/* 表格整体样式 */
.orderRefund-table {
  margin-bottom: 20px;
  font-size: 13px;
  border: 1px solid #ebeef5;
}

/* 表头样式 */
.orderRefund-table th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
  text-align: center;
  white-space: nowrap;
}

/* 单元格样式 */
.el-table td {
  text-align: center;
  padding: 10px 0;
  border-color: #ebeef5;
}

/* 操作按钮的间距调整 */
button.el-button {
  margin: 2px;
  width: 80px; /* 固定按钮宽度 */
}
.pagination-container{
  align-items: center;
  justify-content: center;  /* 居中 */
  display: flex;   /* 使其成为一个flex容器 */
  margin-top: 10px;
}
.button-container {
  display: flex;
  margin-left: 30px;
  width: 100px;
  background-color: #f5f7fa;
  margin-bottom: 20px;
  margin-top: 20px;
}

.button-container .btn_add{
  margin-right: 10px;
  text-align: center;
  font-size: 16px;
  width: 100px;
  border-top-left-radius: 5px;
}

.button-container .btb_del{
  margin-right: 10px;
  text-align: center;
  font-size: 14px;
  width: 150px;
  border-top-left-radius: 5px;
}
.order-list{
  padding: 0;
}
.order-table{
  margin-top: 20px;
}
</style>
